package io.itit.ecp.admin.common.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class JsonUtils {

    private static final com.fasterxml.jackson.databind.Module[] JAVA8_MODULE;

    private static ObjectMapper mapper;

    static {
        List<com.fasterxml.jackson.databind.Module> moduleList = new ArrayList<>();

        JavaTimeModule JAVA_TIME_MODULE = new JavaTimeModule();
        JAVA_TIME_MODULE.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        JAVA_TIME_MODULE.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        JAVA_TIME_MODULE.addSerializer(LocalDate.class,
                new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        JAVA_TIME_MODULE.addDeserializer(LocalDate.class,
                new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        JAVA_TIME_MODULE.addSerializer(LocalTime.class,
                new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        JAVA_TIME_MODULE.addDeserializer(LocalTime.class,
                new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        moduleList.add(JAVA_TIME_MODULE);
        moduleList.add(new Jdk8Module());
        JAVA8_MODULE = moduleList.toArray(new com.fasterxml.jackson.databind.Module[0]);
    }

    private static ObjectMapper getMapper() {
        if (Objects.isNull(mapper)) {
            synchronized (JsonUtils.class) {
                if (Objects.isNull(mapper)) {
                    ObjectMapper m = new ObjectMapper();
                    configure(m);
                    mapper = m;
                }
            }
        }
        return mapper;
    }

    public static void configure(ObjectMapper om) {
        om.setDateFormat(StdDateFormat.instance)
                .setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"))
                .setLocale(Locale.CHINA)
                .enable(JsonReadFeature.ALLOW_JAVA_COMMENTS.mappedFeature())
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
                .configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false)
                .registerModules(JAVA8_MODULE);
    }

    @SneakyThrows(value = {JsonProcessingException.class})
    public static String serialize(Object obj) {
        return getMapper().writeValueAsString(obj);
    }

    @SneakyThrows(value = {Exception.class})
    public static <T> T deserialize(String json, Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return getMapper().readValue(json, clazz);
    }

    @SneakyThrows(value = {Exception.class})
    public static <T> List<T> deserializeList(String json, Class<T> clazz) {
        return deserialize(json, new TypeReference<ArrayList<T>>() {
        });
    }

    @SneakyThrows(value = {Exception.class})
    public static <T> Set<T> deserializeSet(String json, Class<T> clazz) {
        return deserialize(json, new TypeReference<Set<T>>() {
        });
    }

    @SneakyThrows(value = {Exception.class})
    public static <T> T deserialize(String json, TypeReference<T> type) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        ObjectMapper mapper = getMapper();
        return mapper.readValue(json, type);
    }

    @SneakyThrows(value = {Exception.class})
    public static <K, V> Map<K, V> deserializeMap(String json,
                                                  Class<K> keyClass, Class<V> valueClass) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        ObjectMapper mapper = getMapper();
        MapType mapType = mapper.getTypeFactory()
                .constructMapType(HashMap.class, keyClass, valueClass);
        return mapper.readValue(json, mapType);
    }

    @SneakyThrows(value = {Exception.class})
    public static <K, V> List<Map<K, V>> deserializeListMap(String json,
                                                            Class<K> keyClass, Class<V> valueClass) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        ObjectMapper mapper = getMapper();
        MapType mapType = mapper.getTypeFactory()
                .constructMapType(HashMap.class, keyClass, valueClass);
        return mapper.readValue(json, mapper.getTypeFactory().constructParametricType(List.class, mapType));
    }

}
